package by.dezhits.liltweets.fragment;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import by.dezhits.liltweets.ContextHolder;
import by.dezhits.liltweets.PageActivity;
import by.dezhits.liltweets.R;
import by.dezhits.liltweets.WebActivity;
import by.dezhits.liltweets.adapter.TweetCursorAdapter;
import by.dezhits.liltweets.api.TwitterAPI;
import by.dezhits.liltweets.content.contract.TweetContract;
import by.dezhits.liltweets.http.HttpRequestBuilder;
import by.dezhits.liltweets.notifications.NotificationsHelper;
import by.dezhits.liltweets.service.HttpService;

import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;

public class HomePageFragment extends ListFragment implements OnScrollListener {

	private boolean loading = true;
	private int previousTotal = 0;

	private PullToRefreshListView mListView;

	private BroadcastReceiver mBroadcastReceiver;

	private TweetCursorAdapter tweetCursorAdapter;
	
	private final static String RETWEET_FAILED = "Retweet failed";
	private final static String RETWEET_SUCCESSFUL = "Retweet succesful";
	private final static String DELETE_FAILED = "Delete failed";
	private final static String DELETE_SUCCESSFUL = "Delete successful";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// setRetainInstance(true);
		View view = inflater.inflate(R.layout.fragment_homepage, null);
		View footerView = inflater.inflate(
				R.layout.fragment_homepage_footerview, null);
		footerView.setClickable(false);

		mListView = (PullToRefreshListView) view
				.findViewById(android.R.id.list);
		mListView.addFooterView(footerView);
		mListView.setOnScrollListener(this);

		mListView.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				Uri uri = TweetContract.TweetsColumns.CONTENT_URI;
				Cursor cursor = HomePageFragment.this
						.getActivity()
						.getContentResolver()
						.query(uri,
								null,
								null,
								null,
								TweetContract.TweetsColumns.ID
										+ " DESC limit 1");
				long l = 0;
				try {
					cursor.moveToFirst();
					l = cursor.getLong(cursor
							.getColumnIndex(TweetContract.TweetsColumns.ID));
				} catch (Exception e) {
					// Ignored because checked below while adding query
					// parametrs
				}
				Intent intent = new Intent(HomePageFragment.this.getActivity(),
						HttpService.class);
				HttpRequestBuilder httpRequestBuilder = new HttpRequestBuilder();
				httpRequestBuilder.setType(HttpRequestBuilder.Type.GET);
				httpRequestBuilder
						.setTwitterRequest(HttpRequestBuilder.TwitterRequest.STATUSES_HOME_TIMELINE);
				httpRequestBuilder
						.setUrl(TwitterAPI.URL.TWITTER_STATUSES_HOME_TIMELINE_URL);
				httpRequestBuilder.appendQueryParameter(
						TwitterAPI.QueryParametr.COUNT,
						TwitterAPI.MAX_TWEETS_PER_REQUEST);
				httpRequestBuilder.appendQueryParameter(
						TwitterAPI.QueryParametr.INCLUDE_ENTITIES, getString(R.string.t));
				if (l != 0)
					httpRequestBuilder.appendQueryParameter(
							TwitterAPI.QueryParametr.SINCE_ID,
							String.valueOf(l));
				intent.putExtra(HttpService.HTTP_REQUEST_BUILDER,
						httpRequestBuilder);
				getActivity().startService(intent);
			}
		});

		mBroadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				NotificationCompat.Builder nb;
				NotificationManager nm;
				if (action.equals(HttpService.ACTION_ON_ERROR_HOMEPAGE)) {
					Toast.makeText(
							HomePageFragment.this.getActivity(),
							intent.getStringExtra(HttpService.EXTRA_KEY_MESSAGE),
							Toast.LENGTH_SHORT).show();
					mListView.onRefreshComplete();

				} else if (action
						.equals(HttpService.ACTION_ON_SUCCESS_HOMEPAGE)) {
					mListView.onRefreshComplete();
				} else if (action.equals(HttpService.ACTION_ON_ERROR_RETWEET)) {
					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(RETWEET_FAILED)
							.setTicker(RETWEET_FAILED);
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.RETWEET, nb.build());
					nm.cancel(NotificationsHelper.RETWEET);

				} else if (action.equals(HttpService.ACTION_ON_SUCCESS_RETWEET)) {
					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(RETWEET_SUCCESSFUL)
							.setTicker(RETWEET_SUCCESSFUL);
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.RETWEET, nb.build());
					nm.cancel(NotificationsHelper.RETWEET);
				} else if (action.equals(HttpService.ACTION_ON_SUCCESS_DESTROY)) {

					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(DELETE_SUCCESSFUL)
							.setTicker(DELETE_SUCCESSFUL);
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.DELETE_TWEET, nb.build());
					nm.cancel(NotificationsHelper.DELETE_TWEET);
				}

				else if (action.equals(HttpService.ACTION_ON_ERROR_DESTROY)) {
					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(DELETE_FAILED)
							.setTicker(DELETE_FAILED);
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.DELETE_TWEET, nb.build());
					nm.cancel(NotificationsHelper.DELETE_TWEET);

				}

				else if (action.equals(HttpService.ACTION_ON_SUCCESS_USERPAGE)) {

					intent.setClass(HomePageFragment.this.getActivity(),
							PageActivity.class);
					startActivity(intent);

				} else if (action.equals(HttpService.ACTION_ON_ERROR_USERPAGE)) {

					Toast.makeText(HomePageFragment.this.getActivity(),
							intent.getStringExtra(HttpService.EXTRA_KEY_MESSAGE), Toast.LENGTH_LONG)
							.show();

				}

			}
		};
		IntentFilter filter = new IntentFilter();
		filter.addAction(HttpService.ACTION_ON_ERROR_HOMEPAGE);
		filter.addAction(HttpService.ACTION_ON_SUCCESS_HOMEPAGE);
		filter.addAction(HttpService.ACTION_ON_ERROR_RETWEET);
		filter.addAction(HttpService.ACTION_ON_SUCCESS_RETWEET);
		filter.addAction(HttpService.ACTION_ON_ERROR_DESTROY);
		filter.addAction(HttpService.ACTION_ON_SUCCESS_DESTROY);
		filter.addAction(HttpService.ACTION_ON_ERROR_USERPAGE);
		filter.addAction(HttpService.ACTION_ON_SUCCESS_USERPAGE);
		getActivity().registerReceiver(mBroadcastReceiver, filter);

		tweetCursorAdapter = new TweetCursorAdapter(this.getActivity(), null);
		this.setListAdapter(tweetCursorAdapter);
		getLoaderManager().initLoader(0, null, new LoaderCallbacks<Cursor>() {

			@Override
			public Loader<Cursor> onCreateLoader(int paramInt,
					Bundle paramBundle) {
				return new CursorLoader(HomePageFragment.this.getActivity(),
						TweetContract.TweetsColumns.CONTENT_URI, null, null,
						null, TweetContract.TweetsColumns.ID + " DESC");
			}

			@Override
			public void onLoadFinished(Loader<Cursor> paramLoader, Cursor paramD) {
				tweetCursorAdapter.swapCursor(paramD);

			}

			@Override
			public void onLoaderReset(Loader<Cursor> paramLoader) {
				tweetCursorAdapter.swapCursor(null);
			}
		});

		return view;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(mBroadcastReceiver);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (loading) {
			if (totalItemCount > previousTotal) {
				loading = false;
				previousTotal = totalItemCount;
			}
		}
		if (!loading && totalItemCount - visibleItemCount == firstVisibleItem
				&& firstVisibleItem != 0) {
			loading = true;
			previousTotal = totalItemCount;
			Uri uri = TweetContract.TweetsColumns.CONTENT_URI;
			Cursor cursor = this
					.getActivity()
					.getContentResolver()
					.query(uri, null, null, null,
							TweetContract.TweetsColumns.ID + " limit 1");
			long l = 0;
			try {
				cursor.moveToFirst();
				l = cursor.getLong(cursor
						.getColumnIndex(TweetContract.TweetsColumns.ID));
			} catch (Exception e) {
				// Ignored because checked below while adding query parametrs
			}
			Intent intent = new Intent(this.getActivity(), HttpService.class);
			HttpRequestBuilder httpRequestBuilder = new HttpRequestBuilder();
			httpRequestBuilder.setType(HttpRequestBuilder.Type.GET);
			httpRequestBuilder
					.setTwitterRequest(HttpRequestBuilder.TwitterRequest.STATUSES_HOME_TIMELINE);
			httpRequestBuilder
					.setUrl(TwitterAPI.URL.TWITTER_STATUSES_HOME_TIMELINE_URL);
			httpRequestBuilder.appendQueryParameter(
					TwitterAPI.QueryParametr.COUNT, TwitterAPI.NORMAL_TWEETS_PER_REQUEST);
			httpRequestBuilder.appendQueryParameter(
					TwitterAPI.QueryParametr.INCLUDE_ENTITIES, getString(R.string.t));
			if (l != 0) {
				httpRequestBuilder.appendQueryParameter(
						TwitterAPI.QueryParametr.MAX_ID, String.valueOf(l));
			}
			intent.putExtra(HttpService.HTTP_REQUEST_BUILDER,
					httpRequestBuilder);
			this.getActivity().startService(intent);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onListItemClick(ListView l, final View v, int position,
			final long id) {
		AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
		View view = getActivity().getLayoutInflater().inflate(
				R.layout.view_dialog_tweet_onclick, null);
		adb.setView(view);
		adb.setTitle(getString(R.string.what_to_do));
		final AlertDialog ad = adb.create();

		Button followLink = (Button) view.findViewById(R.id.btn_follow_link);
		Button retweet = (Button) view.findViewById(R.id.btn_retweet);
		Button deleteTweet = (Button) view.findViewById(R.id.btn_delete_tweet);

		Cursor cursor = (Cursor) l.getItemAtPosition(position);

		final int tweetUserId = Integer.parseInt(cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.USER_ID)));
		int currentSelectionUserId = Integer.parseInt(ContextHolder
				.getInstance()
				.getContext()
				.getSharedPreferences(getString(R.string.user_details),
						Context.MODE_PRIVATE)
				.getString(getString(R.string.user_id), ""));
		if (tweetUserId == currentSelectionUserId) {
			deleteTweet.setVisibility(View.VISIBLE);
			retweet.setVisibility(View.GONE);
		}

		final String link = cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.LINK));

		if (link != null) {
			followLink.setVisibility(View.VISIBLE);
		}

		View.OnClickListener onClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent;
				HttpRequestBuilder httpRequestBuilder;
				NotificationCompat.Builder nb;
				NotificationManager nm;
				switch (v.getId()) {
				case R.id.btn_follow_link:
					intent = new Intent(HomePageFragment.this.getActivity(),
							WebActivity.class);
					intent.putExtra(getString(R.string.link), link);
					HomePageFragment.this.getActivity().startActivity(intent);
					ad.dismiss();
					break;
				case R.id.btn_retweet:
					intent = new Intent(HomePageFragment.this.getActivity(),
							HttpService.class);
					httpRequestBuilder = new HttpRequestBuilder();
					httpRequestBuilder.setType(HttpRequestBuilder.Type.POST);
					httpRequestBuilder
							.setTwitterRequest(HttpRequestBuilder.TwitterRequest.STATUSES_RETWEET);
					httpRequestBuilder
							.setUrl(TwitterAPI.URL.TWITTER_STATUSES_RETWEET_URL
									+ String.valueOf(id) + getString(R.string.json_format));
					intent.putExtra(HttpService.HTTP_REQUEST_BUILDER,
							httpRequestBuilder);
					HomePageFragment.this.getActivity().startService(intent);
					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(getString(R.string.retweeting_in_process))
							.setTicker(getString(R.string.retweeting_in_process));
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.RETWEET, nb.build());
					nm.cancel(NotificationsHelper.RETWEET);
					ad.dismiss();
					break;
				case R.id.btn_delete_tweet:
					intent = new Intent(HomePageFragment.this.getActivity(),
							HttpService.class);
					httpRequestBuilder = new HttpRequestBuilder();
					httpRequestBuilder.setType(HttpRequestBuilder.Type.POST);
					httpRequestBuilder
							.setTwitterRequest(HttpRequestBuilder.TwitterRequest.STATUSES_DESTROY);
					httpRequestBuilder
							.setUrl(TwitterAPI.URL.TWITTER_STATUSES_DESTROY_URL
									+ String.valueOf(id) + getString(R.string.json_format));
					intent.putExtra(HttpService.HTTP_REQUEST_BUILDER,
							httpRequestBuilder);
					HomePageFragment.this.getActivity().startService(intent);
					nb = new NotificationCompat.Builder(ContextHolder
							.getInstance().getContext())
							.setSmallIcon(android.R.drawable.star_on)
							.setContentText(getString(R.string.deleting_in_process))
							.setTicker(getString(R.string.deleting_in_process));
					nm = (NotificationManager) ContextHolder.getInstance()
							.getContext()
							.getSystemService(Context.NOTIFICATION_SERVICE);
					nm.notify(NotificationsHelper.DELETE_TWEET, nb.build());
					nm.cancel(NotificationsHelper.DELETE_TWEET);
					ad.dismiss();
					break;
				}
			}
		};
		followLink.setOnClickListener(onClickListener);
		retweet.setOnClickListener(onClickListener);
		deleteTweet.setOnClickListener(onClickListener);
		ad.show();
	}

}
